package org.ltt.rbac.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.ltt.rbac.model.User;
import org.ltt.rbac.utils.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * @Author: dujun
 * @Date: 2020/5/21 10:57
 * 登录状态校验
 */
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {
    /**
     * 认证流程：
     *  1、确认是否含有token，如果没有重定向至登录页面
     *  2、如果含有token，则验证token是否有效
     *  3、如果含有token，则验证token的正确性
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1、首先确认是否含有token，如果没有重定向至登录页面
        String token = request.getHeader("_acsToken");
        if (StringUtils.isEmpty(token)) {
            // 重定向至登录页面 ，或者将 错误码返回给前端 -- 前后端分离
            filterChain.doFilter(request, response);
            return;
        }
        // 2、如果含有token，则验证token是否有效
        //解析token
        User user = new User() ;
        user.setAuthorities(List.of((GrantedAuthority) () -> "ROLE_ADMIN"));
        user.setUsername("admin");
        user.setPassword("123456");
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null,null);
        //将认证信息存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
